<template>
  <!-- 单条折线图与多条柱形图 -->
  <div>
    <div ref="fullScreenBox" :id="chartId" class="chart"></div>
  </div>
</template>

<script>
import { mapState } from "vuex";
import Ecolors from "@/utils/chartColors";
import { resize, spaceTxt, toolboxFullScreen } from "@/utils/utils";
import * as echarts from 'echarts'

export default {
  mixins: [resize],
  props: {
    chartId: {
      type: String,
    },
    chartData: {
      type: Object,
    },
  },
  data() {
    return {
      chart: null,
      graphType: "bar",
      colors: [],
      xData: [],
      yData: [],
      legendData: [],
    };
  },
  computed: {
    ...mapState(["curChartConfig"]),
  },
  watch: {
    curChartConfig: {
      deep: true,
      handler: function () {
        this.getCurChartConfig();
      },
    },
    chartData() {
      if (Object.keys(this.chartData).length <= 0) {
        if (this.chart) this.chart.clear();
      } else {
        this.getCurChartConfig();
      }
    },
  },
  mounted() {
    this.chart = this.$echarts.init(document.getElementById(this.chartId));
    this.getCurChartConfig();
  },
  methods: {
    getCurChartConfig() {
      if (Object.keys(this.curChartConfig).length > 0) {
        let colors = [];
        this.curChartConfig.colors.forEach((v) => {
          colors.push(v.color);
        });
        this.colors = [...colors, ...Ecolors.color];
        let graphType = this.curChartConfig.graphType;
        if (this.curChartConfig.graphType === "bar1") {
          graphType = "bar";
        } else if (this.curChartConfig.graphType === "bar2") {
          graphType = "bar";
        }
        this.graphType = graphType;
      }
      if (Object.keys(this.chartData).length > 0) {
        this.init();
      }
    },
    getSeriesData() {
      let seriesData = {
        apd: [],
        isd: [],
        xarr: [],
      };

      let newChartData = JSON.parse(JSON.stringify(this.chartData));
      let xarr = [];
      newChartData.apd.map((item) => {
        xarr.push(item.key_as_string);
      });
      newChartData.isd.map((item) => {
        xarr.push(item.key_as_string);
      });
      xarr = Array.from(new Set(xarr));
      xarr = xarr.sort((a, b) => {
        var dateA = new Date(a);
        var dateB = new Date(b);
        return dateA - dateB;
      });
      let apd = [];
      let isd = [];
      xarr.map((item) => {
        let i = newChartData.apd.findIndex((it) => {
          return item == it.key_as_string;
        });
        i > -1 ? apd.push(newChartData.apd[i].doc_count) : apd.push(0);
      });
      xarr.map((item) => {
        let i = newChartData.isd.findIndex((it) => {
          return item == it.key_as_string;
        });
        i > -1 ? isd.push(newChartData.isd[i].doc_count) : isd.push(0);
      });

      seriesData = {
        apd: apd,
        isd: isd,
        xarr: xarr,
      };

      return seriesData;
    },
    init() {
      let seriesData = this.getSeriesData();
      // 轴线
      let xAxisLine = {
        lineStyle: {
          color:
            this.curChartConfig["axisLine"] &&
            this.curChartConfig["axisLine"].checked
              ? this.curChartConfig["axisLine"].color
              : "#77777",
          width: 1,
          type:
            this.curChartConfig["axisLine"] &&
            this.curChartConfig["axisLine"].checked
              ? this.curChartConfig["axisLine"].type
              : "solid",
        },
      };
      // x轴分隔线
      let xSplitLine = {
        show:
          this.curChartConfig["xGridLine"] &&
          this.curChartConfig["xGridLine"].checked,
        lineStyle: {
          color:
            (this.curChartConfig["xGridLine"] &&
              this.curChartConfig["xGridLine"].color) ||
            "#f0f1f3",
          type:
            this.curChartConfig["xGridLine"] &&
            this.curChartConfig["xGridLine"].type,
        },
      };
      // y轴分隔线
      let ySplitLine = {
        show:
          this.curChartConfig["yGridLine"] &&
          this.curChartConfig["yGridLine"].checked,
        lineStyle: {
          color:
            (this.curChartConfig["yGridLine"] &&
              this.curChartConfig["yGridLine"].color) ||
            "#f0f1f3",
          type: this.curChartConfig["yGridLine"].type,
        },
      };
      // 背景色
      let backgroundColor =
        this.curChartConfig["showBgColor"] &&
        this.curChartConfig["showBgColor"].checked
          ? this.curChartConfig["showBgColor"].color
          : "#fff";

      const hexToRgba = (hex, opacity) => {
        let rgbaColor = "";
        let reg = /^#[\da-f]{6}$/i;
        if (reg.test(hex)) {
          rgbaColor = `rgba(${parseInt("0x" + hex.slice(1, 3))},${parseInt(
            "0x" + hex.slice(3, 5)
          )},${parseInt("0x" + hex.slice(5, 7))},${opacity})`;
        }
        return rgbaColor;
      };
      let color = [
        "#0090FF",
        "#36CE9E",
        "#FFC005",
        "#FF515A",
        "#8B5CFF",
        "#00CA69"
      ];
      let option = {
        color: color,
        title: {
          text: "",
        },
        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "cross",
            label: {
              backgroundColor: "#6a7985",
            },
          },
        },
        toolbox: {
          feature: toolboxFullScreen(this.$refs.fullScreenBox),
        },
        legend: {
          data: ["申请趋势", "公开趋势"],
        },
        // 背景色
        backgroundColor: "#fff",
        toolbox: {
          feature: {
            // saveAsImage: {}
          },
        },
        xAxis: [
          {
            type: "category",
            boundaryGap: false,
            // axisLine: xAxisLine,
            data: seriesData.xarr,
            // splitLine: xSplitLine,
          },
        ],
        yAxis: [
          {
            type: "value",
            // 分隔线
            splitLine: ySplitLine,
          },
        ],
        smooth: true,
        series: [
          {
            name: "申请趋势",
            type: "line",
            // stack: "Total",
            smooth: true,
            zlevel: 3,
            // emphasis: {
            //   focus: "series",
            // },
            lineStyle: {
              normal: {
                color: color[0],
                shadowBlur: 3,
                shadowColor: hexToRgba(color[0], 0.5),
                shadowOffsetY: 8,
              },
            },
            areaStyle: {
              normal: {
                color: new echarts.graphic.LinearGradient(
                  0,
                  0,
                  0,
                  1,
                  [
                    {
                      offset: 0,
                      color: hexToRgba(color[0], 0.6),
                    },
                    {
                      offset: 1,
                      color: hexToRgba(color[0], 0.1),
                    },
                  ],
                  false
                ),
                shadowColor: hexToRgba(color[0], 0.1),
                shadowBlur: 10,
              },
            },
            data: seriesData.apd,
          },
          {
            name: "公开趋势",
            type: "line",
            // stack: "Total",
            smooth: true,
            // emphasis: {
            //   focus: "series",
            // },
            zlevel: 3,
            lineStyle: {
              normal: {
                color: color[1],
                shadowBlur: 3,
                shadowColor: hexToRgba(color[1], 0.5),
                shadowOffsetY: 8,
              },
            },
            areaStyle: {
              normal: {
                color: new echarts.graphic.LinearGradient(
                  0,
                  0,
                  0,
                  1,
                  [
                    {
                      offset: 0,
                      color: hexToRgba(color[1], 0.6),
                    },
                    {
                      offset: 1,
                      color: hexToRgba(color[1], 0.1),
                    },
                  ],
                  false
                ),
                shadowColor: hexToRgba(color[1], 0.1),
                shadowBlur: 10,
              },
            },
            data: seriesData.isd,
          },
        ],
      };
      if (this.graphType !== "pie") {
        option.tooltip.trigger = "axis";
        // option.color = this.colors;
        option.grid = {
          top: "40px",
          right: "40px",
          left: "40px",
          bottom: "40px",
          containLabel: true,
        };
      } else {
        let formatter = (params) => {
          let str = `${params.marker}${params.data.name}：${params.data.value}`;
          return str;
        };
        option.tooltip.trigger = "item";
        option.tooltip.formatter = formatter;
        option.xAxis.show = false;
        option.yAxis.show = false;
      }
      this.chart.clear();
      this.chart.setOption(option);
      this.$emit("chartDom", this.chart);

      // 点击进行对比分析
      this.chart.off("click");
      this.chart.on("click", (params) => {
        let dataIndex = params.dataIndex;
        let op = this.chart.getOption();
        op.series[0].data.forEach((v, i) => {
          if (i == dataIndex) {
            if (v.custom_selected === true) {
              v.itemStyle.color = v.custom_color;
            } else {
              v.itemStyle.color = "red";
            }
            v.custom_selected = !v.custom_selected;
          }
        });
        this.getContrastiveData(op);
        this.chart.setOption(op);
      });

      // 后台报告下载
      this.chart.on("finished", () => {
        let tempId = this.$route.query.tempId;
        if (tempId) {
          this.getEchartImg(this.chart.getDataURL());
        }
      });
    },
    getEchartImg(base) {
      let dom = document.getElementById("echartImgFinished");
      if (dom) {
        document.getElementById("app").removeChild(dom);
      }
      window.echartImg = base;
      let _echartImg = document.createElement("div");
      _echartImg.setAttribute("id", "echartImgFinished");
      document.getElementById("app").appendChild(_echartImg);
    },
    // 保存对比分析数据
    getContrastiveData(option) {
      let arr = [];
      option.series[0].data.forEach((v, i) => {
        if (v.custom_selected === true) {
          arr.push(v);
        }
      });
      this.$emit("contrastiveData", arr);
    },
  },

  destroyed() {
    this.chart.dispose();
    this.chart = null;
  },
};
</script>

<style lang="scss" scoped>
// .chart {
//   background-color: #fff;
// }
</style>
